import os
import sys
import webbrowser

import qt_material
from PySide6.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QTableWidgetItem,
    QVBoxLayout,
)


class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.resize(400, 300)

        self.init_widget()
        self.init_signal()
        self.init_getdata()
        self.init_layout()

    def init_widget(self):
        # tablewidget
        self.table = QTableWidget()
        self.table.setColumnCount(2)
        self.table.setHorizontalHeaderLabels(["网站", "Url"])
        self.table.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeMode.Stretch
        )
        self.table.setAlternatingRowColors(True)
        self.table.setEditTriggers(
            QAbstractItemView.EditTrigger.NoEditTriggers
        )  # 无法编辑

    def init_getdata(self):
        row_count = self.table.rowCount()
        self.table.setRowCount(row_count + 1)
        self.table.setItem(0, 0, QTableWidgetItem("百度"))
        self.table.setItem(0, 1, QTableWidgetItem("https://www.baidu.com/"))

        row_count = self.table.rowCount()
        self.table.setRowCount(row_count + 1)
        self.table.setItem(1, 0, QTableWidgetItem("腾讯视频"))
        self.table.setItem(1, 1, QTableWidgetItem("https://v.qq.com/"))

    def init_signal(self):
        self.table.cellDoubleClicked.connect(self.open_url)  # 双击打开网页

    def init_layout(self):
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.table)
        self.setLayout(v_layout)

    def open_url(self, row, column):
        print(f"{row} {column}")
        if int(column) == 1:
            url = self.table.item(row, column).text()
            webbrowser.open(url)


if __name__ == "__main__":
    os.environ["QT_IM_MODULE"] = "ibus"  # mac系统解决输入法不兼容

    app = QApplication(sys.argv)
    qt_material.apply_stylesheet(app, theme="light_pink.xml")
    window = Window()
    window.show()
    sys.exit(app.exec())